﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Emgu.CV;
using Incendios0_1.Camera.wpfdatamanager;
using AsyncCamera.Camera.Structure;
using AsyncCamera.Camera.media;
using WebCam_Capture;
using Emgu.CV.Structure;
using System.Windows.Media.Imaging;

namespace Incendios0_1.Camera.media.sources
{
    class WebCamSource:MediaSource
    {
        [System.Runtime.InteropServices.DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr handle);

        WebCamCapture reader;
        private double counter;

        public WebCamSource(AbstractCamera camera)
            : base()
        {
            currentState = MediaState.Stop;
            attachCamera(camera);
            counter = 0;
        }

        public void attachCamera(AbstractCamera camera)
        {
            if (currentState == MediaState.Pause || currentState == MediaState.Stop)
            {
                AttachedCamera = camera;
                reader = new WebCamCapture();
                reader.FrameNumber = ((ulong)(0ul));
                reader.TimeToCapture_milliseconds = 30;
                reader.ImageCaptured += new WebCamCapture.WebCamEventHandler(Tick);
            }
        }

        public override void Start()
        {
            reader.TimeToCapture_milliseconds = 30;
            reader.Start(0);
            currentState = MediaState.Play;
        }

        public override void Stop()
        {
            reader.Stop();
            currentState = MediaState.Stop;
        }

        public override void Pause()
        {
            reader.Stop();
            currentState = MediaState.Pause;
        }

        protected void Tick(object sender, WebcamEventArgs e)
        {
            Frame newframe = new Frame();
            newframe.Id = counter;
            newframe.Image = new Image<Bgr, Byte>((System.Drawing.Bitmap)e.WebCamImage);
            Frame = newframe;
        }

        protected override void Tick(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        public static BitmapSource LoadBitmap(System.Drawing.Bitmap source)
        {
            BitmapSource bs;
            IntPtr ip;
            ip = source.GetHbitmap();
            bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, System.Windows.Int32Rect.Empty,
                System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
            DeleteObject(ip);
            return bs;

        }
    }
}
